package middlerwares

import (
	"context"
	"gitee.com/code_batcher/avatar/pkg/auth"
	"github.com/gofiber/fiber/v3"
	"log/slog"
)

func Auth(ctx fiber.Ctx) error {
	authHeader := ctx.Get("Authorization")
	if authHeader == "" {
		return fiber.ErrUnauthorized
	}

	user, err := auth.Parse(authHeader)
	if err != nil {
		slog.Info(err.Error())
		return fiber.ErrForbidden
	}

	// 将解析后的用户名保存到请求上下文中，方便后面读取
	authContext := context.WithValue(context.Background(), "user", user)
	ctx.SetUserContext(authContext)
	return ctx.Next()
}
